/**
 * @desc axios 接口方法
 * http://www.axios-js.com/zh-cn/docs/
 */
import axios from "axios";
import { proxys } from "@/utils";
import { appReducer } from "@/store";
//全局加载参数
export const OPENAPPLOADING = "OpenAppLoading";
export const CLOSEAPPLOADING = "CloseAppLoading";
export const HTTP_SUCCESS_CODE = "SUCCESS";
export const HTTP_ERROR_CODE = "ERROR";
//全局加载-最后一个接口完毕才停止
let LOADINGNUM = 0;
//条件控制是否出现404页面
let ERRORINFO = true;
//时间戳
const date = new Date().getTime();

const DEV_PROXY = proxys().devProxy; //开发
const TEST_PROXY = proxys().testProxy; //测试
const PROV_PROXY = proxys().provProxy; //生产

export const isDev = process.env.NODE_ENV === "development";
const AUTH_TOKEN = window.localStorage.getItem("token");
//默认代理
const defaultProxy = "/proxy";
//校验条件-01,是否含有自定义代理
const proxyRegx = /^\/api-/;
//校验条件-02,是否有http代理
const httpRegx = /^http(s?):\/\//;
//状态类型
const SUCCESS_CODE = 0; //成功
const TOKEN_FAILE = "1001"; //token失效
const LOGIN_OUT = "4001"; //登录已过期
const apiList = [
  { code: "api-juhe", address: "http://apis.juhe.cn" },
  { code: "api-word", address: "http://v.juhe.cn" },
  { code: "api-ipaddress", address: "http://api.map.baidu.com" },
  { code: "api-online-img", address: "https://picsum.photos" },
  { code: "api-down-progress", address: "http://ppt.1ppt.com" },
  { code: "api-bing", address: "https://cn.bing.com" }
];

// 创建一个axios 实例
export const axiosInstance = axios.create({
  // baseURL: isDev ? "" : PROV_PROXY,
  baseURL: "",
  timeout: 30000,
  responseType: "json",
  headers: {
    // Authorization: token//如需token验证，在此处添加token
  }
});

/**
 * @name urlTest
 * @param {String} url 请求地址
 * @description 请求地址处理
 */
export function urlTest(url = "") {
  let urls = "";
  if (isDev) {
    urls = url;
  } else if (httpRegx.test(url) || proxyRegx.test(url)) {
    let arr = url.split("/");
    let httpArr = apiList.filter((v) => v.code === arr[1]) || [];
    let httpStr = httpArr[0] ? httpArr[0].address : "";
    let res = arr.slice(2);
    let finalres = res.join("/");
    // urls = httpStr + "/" + finalres;
    urls = url;
  }
  return urls;
}

// 全局的 axios 默认值
// axios.defaults.baseURL = 'https://api.example.com';
// axios.defaults.headers.common["Access-Control-Allow-Origin"] = "http://localhost";
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加一个请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    LOADINGNUM += 1;
    if (config.ERRORINFO === "UNUSE") {
      ERRORINFO = false;
    } else {
      ERRORINFO = true;
    }
    if (config.OPENLOADIN === "UNUSE") {
      return config;
    } else {
      //全局loading-open
      appReducer.dispatch({ type: OPENAPPLOADING });
      return config;
    }
  },
  (error) => {
    LOADINGNUM += 1;
    appReducer.dispatch({ type: CLOSEAPPLOADING });
    return Promise.reject(error);
  }
);

// 添加一个响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    LOADINGNUM -= 1;
    if (LOADINGNUM === 0) {
      //全局loading-close
      appReducer.dispatch({ type: CLOSEAPPLOADING });
    }
    if (response.data) {
      return response.data;
    } else {
      return Promise.reject(response.data);
    }
  },
  (error) => {
    LOADINGNUM -= 1;
    appReducer.dispatch({ type: CLOSEAPPLOADING });
    return Promise.reject(error);
  }
);

//
export const get = (url, params = null, config = {}) => axiosInstance.get(url, { ...config, params });
export const post = axiosInstance.post;
